package com.example.data;

import android.content.Context;
import android.content.SharedPreferences;

import java.util.concurrent.TimeUnit;


public class Token {

    private String accessToken;
    private String refreshToken;
    private int expiresIn;
    private long expiresAt = -1;

    public boolean saveToSp(Context ctx) {
        long now = System.currentTimeMillis() / 1000;
        return tokenSp(ctx).edit()
                .putString("accessToken", accessToken)
                .putString("refreshToken", refreshToken)
                .putLong("expiresAt", expiresIn + now - 60)
                .putLong("refreshExpiresAt", TimeUnit.DAYS.toSeconds(7) + now - 60)
                .commit();
    }

    public static Token fromSp(Context ctx) {
        SharedPreferences sp = tokenSp(ctx);
        String accessToken = sp.getString("accessToken", null);
        String refreshToken = sp.getString("refreshToken", null);
        if (accessToken == null || refreshToken == null) {
            return null;
        }
        long refreshExpiresAt = sp.getLong("refreshExpiresAt", 0);
        long now = System.currentTimeMillis() / 1000;
        if (refreshExpiresAt < now) {
            return null;
        }
        long expiresAt = sp.getLong("expiresAt", 0);
        Token token = new Token();
        token.accessToken = accessToken;
        token.refreshToken = refreshToken;
        token.expiresAt = expiresAt;
        return token;
    }

    public boolean isValid() {
        return expiresAt < 0 || expiresAt > System.currentTimeMillis() / 1000;
    }

    private static SharedPreferences tokenSp(Context ctx) {
        return ctx.getSharedPreferences("token", Context.MODE_PRIVATE);
    }

    public String getAccessToken() {
        return accessToken;
    }

    public void setAccessToken(String accessToken) {
        this.accessToken = accessToken;
    }

    public String getRefreshToken() {
        return refreshToken;
    }

    public void setRefreshToken(String refreshToken) {
        this.refreshToken = refreshToken;
    }

    public int getExpiresIn() {
        return expiresIn;
    }

    public void setExpiresIn(int expiresIn) {
        this.expiresIn = expiresIn;
    }

}
